package com.icinfo.cloud.provider.punish.common.caseregister;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.core.config.RedisRepository;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.config.RedisUtil;
import com.icinfo.cloud.provider.common.enums.TerritoryCodeEnum;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.common.caseregister.service.IRegisterCommonService;
import com.icinfo.cloud.provider.punish.common.seal.utils.ChongQingInfoUtil;
import com.icinfo.cloud.provider.punish.common.seal.utils.ChongQingPersonInfo;
import com.icinfo.cloud.provider.punish.common.seal.utils.ChongQingPersonInfoUtil;
import com.icinfo.cloud.provider.punish.common.seal.utils.EntLikeInfo;
import com.icinfo.cloud.provider.punish.config.mapper.SysDepartParamMapper;
import com.icinfo.cloud.provider.punish.config.vo.AreaVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.PersonInfoMsgVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseLineInfoQueryDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.RealNameCheckDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.CaseLineInfoVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.RealNameCheckVo;
import com.icinfo.cloud.xzcf.provider.member.org.dto.Org;
import com.icinfo.cloud.xzcf.provider.member.permission.api.PermissionTreeFeignApi;
import com.icinfo.cloud.xzcf.provider.member.permission.dto.PermissionTree;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.web.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 【V1.3.0】公共接口服务
 *
 * @author lxj
 * @date 2022/2/22
 **/
@RestController
@RequestMapping("/punish/common/")
@Slf4j
public class RegisterCommonController extends BaseController {

    @Resource
    private  IRegisterCommonService commonService;
    @Resource
    SysDepartParamMapper sysDepartParamMapper;
    @Resource
    CaseHandlePersonRecordMapper handlePersonRecordMapper;
    @Resource
    private RedisUtil redisUtil;
    @Autowired
    private PermissionTreeFeignApi permissionTreeFeignApi;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private RedisRepository redisRepository;

    /**
     * 立案登记----获取用户登录信息
     *
     * @param
     * @return Result
     * @author lxj
     * @date 2022/2/23
     **/
    @RequestMapping("/getLoginUserInfo")
    public Result<UserDTO> getLoginUserInfo() {
        UserDTO userDTO = UserUtil.getUserInfo();
        if (userDTO == null) {
            return Result.success(450, "未登录或登录信息已失效");
        }
        //更新dingId ,一天只更新一次
        String val = redisRepository.get(userDTO.getDingDingId()+BaseUtil.getNow());
        if(StringUtils.isNotEmpty(userDTO.getDingDingId())&&StringUtils.isEmpty(val)){
           redisRepository.setExpire(userDTO.getDingDingId()+BaseUtil.getNow(), "value",24*3600L);
           handlePersonRecordMapper.updateDingIdByUserId(userDTO.getUserId().toString(),userDTO.getDingDingId());
        }
        return Result.success(userDTO);

    }
    /**
     * 获取用户菜单
     * @author liyafeng
     * @date 2022/8/27
      * @param
     * @return {@link Result< List< PermissionTree>>}
     */
    @RequestMapping("/getPermissionTreeList")
    public Result<List<PermissionTree>> getPermissionTreeList() {
        //List<PermissionTree> getPermissionTreeList = UserUtil.getPermissionTree();
        List<PermissionTree> permissionTrees = new ArrayList<>();
        UserDTO userDTO = UserUtil.getUserInfo();
        //String userName = userDTO.getLoginName();
        String orgCode = userDTO.getOrgCode();
       /* if (redisUtil.existsPermissionKey(orgCode, userName)) {
            System.out.println("orgCode:"+orgCode);
            System.out.println("userName:"+userName);
            String userPermissionKeyValue = redisUtil.getPermission(orgCode, userName);
            permissionTrees = JSONArray.parseArray(userPermissionKeyValue, PermissionTree.class);
            System.out.println("permissionTrees大小:"+permissionTrees.size());
            if(null==permissionTrees||permissionTrees.size()==0){
                redisUtil.delRedis(orgCode, userName);
            }
        } else {*/
            String userId = userDTO.getUserId().toString();
            System.out.println("userId======"+userId);
            System.out.println("orgCode======"+orgCode);
            permissionTrees = permissionTreeFeignApi.getPermissionTree(userId,orgCode);
            /*if(null!=permissionTrees&&permissionTrees.size()>0) {
                redisUtil.putPermissionTrees(orgCode,userName, permissionTrees);
            }
        }*/
        return Result.success(permissionTrees);

    }


    /**
     *  获取登录用户单位信息(含部门，领域列表，机构等信息)
     *
     * @param
     * @return Result
     * @author lxj
     * @date 2022/2/23
     **/
    @RequestMapping("/getUserOrgMsg")
    public Result<Org> getUserOrgMsg() {
        try {
            UserDTO userDTO = UserUtil.getUserInfo();
            if (userDTO == null) {
                return Result.success(450, "未登录或登录信息已失效");
            }
            Org org = commonService.getUserOrgMsg();
            if (org == null) {
                return Result.error("没有找到机构数据");
            }
            return Result.success(org);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 立案登记----获取单位列表
     *
     * @param
     * @return Result
     * @author lxj
     * @date 2022/2/23
     **/
    @RequestMapping("/getUnitTreeList")
    public Result getUnitTreeList(@RequestBody String req) {
        if (StringUtils.isEmpty(req)) {
            return Result.error("请输入查询数据");
        }
        JSONObject object = JSONObject.parseObject(req);
        if (StringUtils.isEmpty(object.getString("tyxydm")) && StringUtils.isEmpty(object.getString("frmc"))) {
            return Result.error("请输入查询数据");
        }
        JSONArray array = new JSONArray();
        List<EntLikeInfo.DataBean.ResultBean> likeEntInfo = ChongQingInfoUtil.getLikeEntInfo(object.getString("frmc"), object.getString("tyxydm"), null);
        if (CollectionUtils.isNotEmpty(likeEntInfo)) {
            for (EntLikeInfo.DataBean.ResultBean resultBean : likeEntInfo) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("frmc",resultBean.getENTNAME());
                jsonObject.put("tyxydm",resultBean.getUNISCID());
                jsonObject.put("fddbr",resultBean.getNAME());
                jsonObject.put("fr_zjhm",resultBean.getCERNO());
                jsonObject.put("cxzt",resultBean.getREGSTATE_CN());
                jsonObject.put("address", resultBean.getDOM());
                array.add(jsonObject);
//                EntBaseInfoVo entBaseInfoVo = new EntBaseInfoVo();
//                entBaseInfoVo.setFrmc(resultBean.getENTNAME());
//                entBaseInfoVo.setFddbr(resultBean.getNAME());
//                entBaseInfoVo.setFrZjlx(resultBean.getCERTYPE());
//                entBaseInfoVo.setFrZjhm(resultBean.getCERNO());
//                // 转换 5 个体 2, 1 内资 1 法人, 8 外资. 3 其他
//                entBaseInfoVo.setFrType(resultBean.getPRITYPE().equals(Constant.STRING_5) ? "2" : resultBean.getPRITYPE().equals(Constant.STRING_1) ? "1" : "3");
//                entBaseInfoVo.setPost("");
//                entBaseInfoVo.setTyxydm(resultBean.getUNISCID());
//                entBaseInfoVo.setZcdz(resultBean.getDOM());
//                entBaseInfoVo.setState(resultBean.getREGSTATE_CN());
//                data.add(entBaseInfoVo);
            }
        }
//        JSONArray array = commonService.getCompanyMsg(object.getString("tyxydm"), object.getString("frmc"));
        if (array.size() == 0) {
            return Result.error("没有对应单位数据");
        }
        return Result.success(array);
    }

    /**
     * 获取登录用户签名信息
     *
     * @param
     * @return Result
     * @author lxj
     * @date 2022/2/23
     **/
    @RequestMapping("/getUserSign")
    public Result getUserSign() {
        UserDTO userDTO = UserUtil.getUserInfo();
        if (userDTO == null) {
            return Result.error("登录信息失效");
        }
        //String signData ="";
        String sign = "";
        try {
            sign = commonService.getHandleSignData(userDTO.getUserId().toString());
        } catch (Exception e) {
            log.info("失败:" + e.toString());
        }
        return Result.success("success", sign);
    }

    /**
     * 通过身份证获取用户具体信息
     *
     * @param idCardObj
     * @return Result
     * @author lxj
     */
    @RequestMapping("/getPersonInfoByIdCard")
    public Result getPersonInfoByIdCard(@RequestBody JSONObject idCardObj) {
        if (ObjectUtils.isEmpty(idCardObj) || StringUtils.isEmpty(idCardObj.getString("idCard"))) {
            return Result.error("idCard 未传递");
        }
//        PersonInfoMsgVo vo = commonService.getPersonInfoByIdCard(idCardObj.getString("idCard"));
        // 重庆个人信息查询
        ChongQingPersonInfo.DataBean.ListBean idCard = ChongQingPersonInfoUtil.getData(idCardObj.getString("idCard"));
        if (idCard == null) {
            return Result.error("查询失败");
        }
        PersonInfoMsgVo vo = new PersonInfoMsgVo();
        vo.setIdCard(idCard.getGmsfhm());
        String address = Optional.ofNullable(idCard.getHkszdxzqh()).orElse("") + Optional.ofNullable(idCard.getHkszdjlx()).orElse("")
                  +  Optional.ofNullable(idCard.getHkszdmph()).orElse("") + Optional.ofNullable( idCard.getHkszdsh()).orElse("");
        vo.setAddress("");
        vo.setBirthday(idCard.getCsrq());
        vo.setGender(idCard.getXb());
        vo.setName(idCard.getXm());
        vo.setNationality(idCard.getGj());
        vo.setAddressDetail(address);
        return Result.success("success", vo);
    }

    /**
     * 通过身份证获取用户具体信息
     *
     */
    @RequestMapping("/getPersonInfoByIdCardChongQing")
    public Result getPersonInfoByIdCardChongQing(@RequestParam @NotEmpty @Validated String sfzhm) {
        // todo 查询身份证的数据信息
        PersonInfoMsgVo vo = new PersonInfoMsgVo();
        ChongQingInfoUtil.getPersonInfo(sfzhm);
        return Result.success("success", vo);
    }

    /**
     * 获取系统区划表数据
     *
     * @return Result
     * @author lxj
     */
    @RequestMapping("/getSysAreaList")
    public Result getSysAreaList() {
        List<AreaVo> list = commonService.getSysAreaList();

        return Result.success("success", list);
    }


    /**
     * 获取机构文书抬头标准名称
     *
     * @return Result  org_standard_name
     * @author lxj
     */
    @RequestMapping("/getOrgStandardName")
    public Result getOrgStandardName() {
        UserDTO userDTO = UserUtil.getUserInfo();
        String orgStandName = commonService.getOrgStandardNameByOrgCode(userDTO.getOrgCode(),userDTO.getDeptCode());
        return Result.success("success", orgStandName);
    }

    /**
     * 【V1.0.0】描述：案由列表列表
     *
     * @param
     * @return Result
     * @author lxj
     * @date 2022-02-22
     */
    /*@RequestMapping("/getCaseReasonList")
    public Result getCaseReasonList() {
        //获取登录人员登录信息
        UserDTO userDTO = UserUtil.getUserInfo();
        Map<String, String> headers = HeaderUtil.headerInfo();
        String response = HttpUtil.createGet(auditPubTreeUrl+"?orgCode="+userDTO.getOrgCode()).addHeaders(headers).execute().body();
        JSONObject jsonObject = JSONObject.parseObject(response);
        if(jsonObject.getInteger("code")!=200){
            return Result.error(jsonObject.getString("message"));
        }
        return Result.success("");
    }

    /**
     * test
     * @author lxj
     * @return
     */
    @RequestMapping("/tt")
    public Result tt() {
        //DingDingUtil.expireMsg("001245", "", "台综执第108号", "2小时", "78436278", "徐总", "徐立峰", "乱丢垃圾", "http://www.baidu.com");
        return Result.success("");
    }

    /**
     * 描述：实名认证
     *
     * @param checkDto 检查dto
     * @return {@link Result<RealNameCheckVo> }
     * @author shishengyao
     * @date 2022/05/17
     */
    @PostMapping("/checkRealName")
    public Result<Object> checkRealName(@RequestBody @Validated RealNameCheckDto checkDto) {
        RealNameCheckVo realNameCheckVo = commonService.checkRealName(checkDto);
        return Result.success("校验成功", realNameCheckVo);
    }

    /**
     * 【V1.3.0】描述：获取条线列表
     *
     * @param queryDto
     * @return {@link Result<Object> }
     * @author shishengyao
     * @date 2022/06/16
     */
    @PostMapping("/getLineInfo")
    public Result<List<CaseLineInfoVo>> getLineInfo(@RequestBody @Validated CaseLineInfoQueryDto queryDto) {
        List<CaseLineInfoVo> caseLineInfoVos = commonService.getCaseLineIInfoList(queryDto);
        return Result.success("查询成功", caseLineInfoVos);
    }

    /**
     * 描述：获取办案人员签名
     *
     * @param userId 用户id
     * @return {@link Result }
     * @author shishengyao
     * @date 2022/08/09
     */
    @GetMapping("/getHandleUserSign")
    public Result getHandleUserSign(@Param("userId") String userId ) {
        String sign = "";
        try {
            sign = commonService.getHandleSignData(userId);
        } catch (Exception e) {
            log.info("失败:" + e.toString());
        }
        return Result.success("success", sign);
    }

    /**
     * 是否进入台州详情页面
     * @author liyafeng
     * @date 2022/11/2
      * @param caseId
     * @return {@link Result}
     */
    @GetMapping("/getIsTzDetailPage")
    public Result getIsTzDetailPage(@Param("caseId") String caseId) {
        String isTzDetailPage="false";
        UserDTO userDTO=UserUtil.getUserInfo();
        CaseMainInfoVo caseMainInfoVo=caseMainInfoMapper.selectCaseMainInfo(caseId);
        String areaCode=userDTO.getAreaCode();
        if(null!=caseMainInfoVo) {
            String territoryCode = caseMainInfoVo.getCaseTerritoryCode();
            if (areaCode.startsWith("3310") && (TerritoryCodeEnum.ZHZF.getCode().equals(territoryCode) || TerritoryCodeEnum.XZJD.getCode().equals(territoryCode))) {
                isTzDetailPage = "true";
            }
        }
        return Result.success("success", isTzDetailPage);
    }


}
